<?php
$prefix = 'wpbl_';
$blogusers = get_users('blog_id=1&role=library-member');
$meta_box = array(
	'id' => 'availablity_box',
	'title' => 'Book Status',
	'page' => 'library',
	'context' => 'normal',
	'priority' => 'low',
	'fields' => array(
			array(
			'name' => 'Select User',
			'id' => $prefix . 'user',
			'type' => 'select',
			'options' => $blogusers
		),
		array(
			'name' => 'Availablity',
			'id' => $prefix . 'availablity',
			'type' => 'radio',
			'options' => array(
				array('name' => 'Available', 'value' => 'Available'),
				array('name' => 'Rented', 'value' => 'Rented')
			)
		)
	)
);

add_action('admin_menu', 'availablity_add_box');

// Add meta box
function availablity_add_box() {
	global $meta_box;
	
	add_meta_box($meta_box['id'], $meta_box['title'], 'availablity_show_box', $meta_box['page'], $meta_box['context'], $meta_box['priority']);
}


// Callback function to show fields in meta box
function availablity_show_box() {
	global $meta_box, $post;

	// Use nonce for verification
	echo '<input type="hidden" name="availablity_meta_box_nonce" value="', wp_create_nonce(basename(__FILE__)), '" />';
	
	echo '<table class="form-table">',
				'<th style="width:20%"><label for="', $meta_box['id'], '">', $meta_box['title'], '</label></th>';

	foreach ($meta_box['fields'] as $field) {
		// get current post meta data
		$meta = get_post_meta($post->ID, $field['id'], true);

		echo '<tr>',
				'<th style="width:20%"><label for="', $field['id'], '">', $field['name'], '</label></th>',
				'<td>';
		switch ($field['type']) {
			case 'select':
				echo '<select name="', $field['id'], '" id="', $field['id'], '">';
				echo '<option class="user-option" value="Everyone">None</option>';
				foreach ($field['options'] as $option) {
echo '<option id="', $option->display_name, '" value="', $option->display_name, '"', $meta == $option->display_name ? ' selected="selected"' : '', '>', $option->display_name, '</option>';
				}
				echo '</select>';
				break;
			case 'radio':
				foreach ($field['options'] as $option) {
					echo '   <input type="radio" name="', $field['id'], '" id="', $option['value'], '" value="', $option['value'], '"', $meta == $option['value'] ? ' checked="checked"' : '', ' />   ', $option['name'];
				}
				break;
		}
		echo 	'<td>',
			'</tr>';
	}	
	echo '</table>';
}


add_action('save_post', 'availablity_save_data');

// Save data from meta box
function availablity_save_data($post_id) {
	global $meta_box;
	
foreach ($meta_box['fields'] as $field) {
		$old = get_post_meta($post_id, $field['id'], true);
		$new = $_POST[$field['id']];
		
		if ($new && $new != $old) {
			update_post_meta($post_id, $field['id'], $new);
		} elseif ('' == $new && $old) {
			delete_post_meta($post_id, $field['id'], $old);
		}
	}
}
//include (WPBL_PLUGIN_PATH.'/quick_edit.php');
